package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录前发送验证码
     *
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        log.info("[手机登录:发送验证码],user:{}", user);

        //获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String validateCode = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("[手机登录:发送验证码],验证码:{}", validateCode);

//            SMSUtils.sendMessage(
//                    "传智健康项目基手机号登录",
//                    "SMS_175532136",
//                    user.getPhone(), validateCode + ""
//            );
            //session.setAttribute(user.getPhone(), validateCode + "");
            //需要将生成的验证码保存到Redis,设置过期时间
            redisTemplate.opsForValue().set(phone,validateCode,5, TimeUnit.MINUTES);
            return R.success("发送成功");
        }
        return R.error("发送失败");
    }

    /**
     * 移动端登录
     *
     * @param mapData
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map mapData, HttpSession session) {
        log.info("[手机登录],map:{}", mapData);

        String phone = (String) mapData.get("phone");
        String code = (String) mapData.get("code");

        //String codeInSession = (String) session.getAttribute(phone);
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);

        if (codeInRedis != null && codeInRedis.equals(code)) {
            LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            userLambdaUpdateWrapper.eq(User::getPhone, phone);
            User one = userService.getOne(userLambdaUpdateWrapper);
            if (one == null) {
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            session.setAttribute("user", one.getId());
            redisTemplate.delete(phone);
            return R.success(one);
        }
        return R.error("登录失败");
    }
}